<template>
  <div class="app-container" id="userContainer">
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input
          placeholder="请输入用户名..."
          v-model="queryForm.query"
          clearable
          @keyup.enter="initUserList(1)"
        ></el-input>
      </el-col>
      <el-button
        type="primary"
        :icon="Search"
        @click="initUserList(1)"
        v-hasPerm="['system:user:query']"
        >搜索</el-button
      >
      <el-button
        type="success"
        :icon="DocumentAdd"
        @click="saveSysUserHandler(-1)"
        v-hasPerm="['system:user:add']"
        >新增</el-button
      >
      <el-button
        type="warning"
        :icon="DocumentAdd"
        @click="exportSysUserHandler"
        v-hasPerm="['system:user:export']"
        >导出</el-button
      >
      <el-popconfirm
        title="您确定批量删除这些记录吗？"
        @confirm="handleDelete(null)"
      >
        <template #reference>
          <el-button
            type="danger"
            :icon="Delete"
            :disabled="delBtnStatus"
            v-hasPerm="['system:user:delete']"
            >批量删除</el-button
          >
        </template>
      </el-popconfirm>
    </el-row>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      :row-style="{ height: '40px' }"
      :cell-style="{ padding: '0px' }"
      @selection-change="handleSelectionChange"
      row-class-name="table-row-cls"
    >
      <el-table-column
        type="selection"
        width="55"
        :selectable="tableRowHandle"
      />
      <el-table-column label="头像" prop="avatar" width="80" align="center">
        <template v-slot="scope">
          <img
            width="40"
            :src="getServerUrl() + '/image/userAvatar/' + scope.row.avatar"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户" align="center" />
      <el-table-column
        prop="email"
        label="邮箱"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column prop="phonenumber" label="手机号" align="center" />
      <el-table-column prop="status" label="状态" align="center">
        <template v-slot="{ row }">
          <el-switch
            v-model="row.status"
            @change="statusChangeHandle(row)"
            active-value="0"
            inactive-value="1"
            size="small"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width="180"
      />
      <el-table-column prop="action" label="操作" width="150" align="center">
        <template v-slot="scope">
          <div style="display: flex; align-items: center">
            <el-button
              type="primary"
              :icon="Edit"
              @click="saveSysUserHandler(scope.row.id)"
              v-hasPerm="['system:user:edit']"
              size="small"
              link
              >编辑</el-button
            >
            <el-dropdown
              size="small"
              @command="(command) => handleCommand(command, scope.row)"
              v-hasPerm="[
                'system:user:resetPwd',
                'system:user:role',
                'system:user:delete',
              ]"
            >
              <el-button size="small" type="primary" link
                >更多<el-icon><DArrowRight /></el-icon
              ></el-button>
              >
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-hasPerm="['system:user:resetPwd']"
                    command="handleResetPwd"
                  >
                    <el-button
                      type="warning"
                      :icon="RefreshRight"
                      size="small"
                      link
                      >重置密码</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-hasPerm="['system:user:role']"
                    command="handleAuthRole"
                  >
                    <el-button type="primary" :icon="Tools" size="small" link
                      >分配角色</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-hasPerm="['system:user:delete']"
                    command="handleDelete"
                  >
                    <el-button
                      v-if="
                        scope.row.sysRoleList.some((item) => item.id == 1)
                          ? false
                          : true
                      "
                      type="danger"
                      :icon="Delete"
                      v-hasPerm="['system:user:delete']"
                      size="small"
                      link
                      >删除</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        :small="false"
        :disabled="false"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <user-dialog
      v-model="dialogVisible"
      :userId="userId"
      :dialogTitle="dialogTitle"
      :dialogVisible="dialogVisible"
      @initUserList="initUserList"
    />
    <role-dialog
      v-model="roleDialogVisible"
      :sysRoleList="sysRoleList"
      :roleDialogVisible="roleDialogVisible"
      :id="userId"
      @initUserList="initUserList"
    />
  </div>
</template>
<script>
export default {
  name: "user",
};
</script>
<script setup>
import { ref, onMounted } from "vue";
import http, { getServerUrl } from "@/utils/request";
import qs from "qs";
import { ElMessage, ElMessageBox } from "element-plus";
import load from "@/utils/load.js"; // 引入

import {
  Delete,
  DocumentAdd,
  Edit,
  RefreshRight,
  Search,
  Tools,
  DArrowRight,
} from "@element-plus/icons-vue";

import UserDialog from "./components/UserDialog";
import RoleDialog from "./components/RoleDialog.vue";

const tableData = ref([]);
const total = ref(0);
const queryForm = ref({
  query: "",
  pageNum: 1,
  pageSize: 5,
});
const dialogVisible = ref(false);
const userId = ref(-1);
const dialogTitle = ref("");
const delBtnStatus = ref(true);
const multipleSelection = ref([]);
const roleDialogVisible = ref(false);
const sysRoleList = ref([]);

const handleRoleDialogValue = (row) => {
  userId.value = row.id;
  sysRoleList.value = row.sysRoleList;
  roleDialogVisible.value = true;
};
const tableRowHandle = (row) => {
  const sysRoleList = row.sysRoleList;
  if (sysRoleList.length) {
    if (sysRoleList.some((item) => item.id == 1)) {
      return false;
    } else {
      return true;
    }
  } else {
    return true;
  }
};

//新增用户
const saveSysUserHandler = (uid) => {
  if (uid > 0) {
    userId.value = uid;
    dialogTitle.value = "编辑用户";
  } else {
    userId.value = -1;
    dialogTitle.value = "新增用户";
  }
  dialogVisible.value = true;
};

const initUserList = async (pageNum) => {
  load.show();
  if (pageNum) queryForm.value.pageNum = pageNum;
  let result = await http.post("sys/user/list", queryForm.value);
  let res = result.data;
  if (res.code == 200) {
    res.data.userList.map((m) => {
      m.rolesStr = m.sysRoleList.map((t) => t.name).join(",");
      return m;
    });
    tableData.value = res.data.userList;
    total.value = res.data.total;
    setTimeout(() => {
      load.hide();
    }, 500);
  } else {
    load.hide();
  }
};
const exportSysUserHandler = async () => {
  let result = await http.exportFile("sys/user/export", queryForm.value);
  let blob = window.URL.createObjectURL(
    new Blob([result.data], {
      type: "xlsx",
    })
  );
  let link = document.createElement("a");
  link.style.display = "none";
  link.href = blob;
  link.setAttribute("download", "test.xlsx");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link); //下载完成移除元素
  window.URL.revokeObjectURL(blob); //释放掉 blob 对象
};
const handleSizeChange = (val) => {
  queryForm.value.pageSize = val;
  console.log("queryForm", queryForm);
  initUserList();
};
const handleCurrentChange = (val) => {
  queryForm.value.pageNum = val;
  initUserList();
};
const handleCommand = (command, row) => {
  switch (command) {
    case "handleResetPwd":
      resetPwdHandler(row.id);
      break;
    case "handleAuthRole":
      handleRoleDialogValue(row);
      break;
    case "handleDelete":
      handleDelete(row);
      break;
    default:
      break;
  }
};

/**
 * 更新用户状态
 */

const statusChangeHandle = async (row) => {
  const res = await http.post("sys/user/updateUserStatus", row);
  const data = res.data;
  if (data.code == 200) {
    ElMessage({
      type: "success",
      message: data.msg,
    });
  } else {
    ElMessage({
      type: "error",
      message: data.msg,
    });
  }
};
const handleSelectionChange = (selection) => {
  // 有选择项才有批量删除
  if (selection.length > 0) delBtnStatus.value = false;
  else delBtnStatus.value = true;
  multipleSelection.value = selection;
};
const handleDelete = async (row) => {
  ElMessageBox.confirm("您确定要删除这个记录吗?", "信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      var userList = [];
      if (row) {
        userList.push(row);
      } else {
        multipleSelection.value.forEach((row) => {
          if (row.id != 1) userList.push(row);
        });
      }
      const res = await http.post("sys/user/delete", userList);
      const data = res.data;
      if (data.code == 200) {
        ElMessage({
          type: "success",
          message: data.msg,
        });
        initUserList(1);
      } else {
        ElMessage({
          type: "error",
          message: data.msg,
        });
      }
    })
    .catch(() => {});
};
const resetPwdHandler = async (id) => {
  ElMessageBox.confirm("您确定要重置密码吗?", "信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await http.get(`sys/user/resetPwd/${id}`);
      const data = res.data;
      if (data.code == 200) {
        ElMessage({
          type: "success",
          message: data.msg,
        });
      } else {
        ElMessage({
          type: "error",
          message: data.msg,
        });
      }
    })
    .catch(() => {});
};
onMounted(() => {
  initUserList();
});
</script>

<style lang="less" scoped>
.app-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 13px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>
<style lang="less">
.table-row-cls {
  .el-button + .el-button {
    margin-left: 0;
  }
}
</style>